
package com.kweative.model.data;

import com.kweative.model.Table;
import com.kweative.model.column.Column;
import com.kweative.model.relation.ISimpleRelation;
import com.kweative.model.relation.Relation;
import com.kweative.type.ICanDoNode;
import com.kweative.type.Node;
import java.sql.SQLException;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author henrik
 */
public class Row<T extends Table> implements Cloneable,ICanDoNode {
    public int __primary = 0;
    private T table;

    protected Row() {
        
    }

    public Row(T tbl) {
        table = tbl;
    }

    public boolean isNew() {
        return __primary == 0;
    }


    public T getTable() {
        return table;
    }
    public <P extends Table> Row<P> getByRelation(Relation<P,T> relation) {
        return relation.getParent().select().using(relation).first();
	}
    public <P extends Table> boolean setByRelation(ISimpleRelation relation,Row<P> row) {
        try {
            if (!isNew())
                getTable().update(__primary).set(relation, row).execute();
            return true;
        } catch (SQLException ex) {
            Logger.getLogger(Row.class.getName()).log(Level.SEVERE, null, ex);
        }
        return false;
	}
    public boolean save() {
        try {
            if (isNew())
                __primary = getTable().insert(this);
            else
                getTable().update(this);
            return true;
        } catch (SQLException ex) {
            Logger.getLogger(Row.class.getName()).log(Level.SEVERE, null, ex);
        }
        return false;
    }

    @Override
    protected Object clone() {
        try {
            return super.clone();
        } catch (CloneNotSupportedException ex) {
            Logger.getLogger(Row.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

	public Node toNode() {
		Node row = new Node(getClass().getSimpleName());
		row.setType(Node.Type.COMPLEX);
		Collection<Column> columns = getTable().getColumns().values();
		for(Column col: columns) {
			try {
				Object value = col.serialize(getClass().getField(col.getName()).get(this));
				row.makeChild(col.getName(),value).setAttribute("type",col.getDataType().getSimpleName()).setType(Node.Type.NAMEVALUE);
			} catch (Exception ex) {
				Logger.getLogger(Row.class.getName()).log(Level.SEVERE, null, ex);
			}
		}

		return row;
	}

}
